package com.example.system.controller;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.starter.security.annotation.PreInnerAuthorize;
import com.example.starter.util.Response;
import com.example.starter.weixin.pojo.PhoneInfo;
import com.example.starter.weixin.pojo.WxPhone;
import com.example.starter.weixin.util.WxUtil;
import com.example.system.api.WeixinApi;
import com.example.system.config.WxAppletAccessTokenStateMachine;
import com.example.system.convert.UserConvert;
import com.example.system.dto.WeixinExtraDto;
import com.example.system.entity.User;
import com.example.system.entity.WeixinExtra;
import com.example.system.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 王令
 * @since 2023/7/13
 */
@RestController
@RequestMapping("/weixin")
@RequiredArgsConstructor
public class WeixinController implements WeixinApi {

    private final WxAppletAccessTokenStateMachine machine;
    private final IUserService userService;

    @PreInnerAuthorize
    @Override
    public Response<Boolean> saveWeixinExtra(WeixinExtraDto weixinExtraDto) {
        final WeixinExtra weixinExtra = UserConvert.INSTANCE.toWeixinExtra(weixinExtraDto);
        userService.saveWeixinExtra(weixinExtra);
        return Response.ok();
    }

    /**
     * 微信用户获取手机号
     * @param code 微信获取的code
     * @return ok
     */
    @GetMapping("/phone-number")
    public Response<PhoneInfo> obtainPhoneNumber(@RequestParam("code") String code) {
        WxPhone wxPhone = WxUtil.obtainPhoneNumber(machine.getAccessToken(), code);
        if (!StrUtil.equals("ok", wxPhone.getErrmsg())) {
            return Response.fail(wxPhone.getErrmsg());
        }
        final PhoneInfo phoneInfo = wxPhone.getPhone_info();
        final User one = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getPhone, phoneInfo.getPhoneNumber()).last("limit 1"));
        // 如果系统中不存在则自动创建用户
        if (ObjUtil.isNull(one)) {
            User user = new User();
            user.setPhone(phoneInfo.getPhoneNumber());
            user.setUsername(userService.nextUid());
            user.setNickname("微信用户" + RandomUtil.randomNumbers(4));
            user.setEnabled(true);
            user.setNonLocked(true);
            userService.save(user);
        }
        return Response.ok(phoneInfo);
    }

    @PreInnerAuthorize
    @Override
    public Response<WeixinExtraDto> loadWeixinExtra(String username) {
        final WeixinExtraDto weixinExtra = userService.findWeixinExtra(username);
        return Response.ok(weixinExtra);
    }
}
